package org.lc.cmd;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.jline.console.CommandMethods;
import org.lc.cmd.impl.DefaultParamsParser;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 命令
 */
@Getter
public abstract class Command {
    protected final String name;

    /**
     * 命令参数
     */
    protected final List<CmdParam> params;

    protected final Config config;

    @Setter
    protected String description;

    public Command(String name, List<CmdParam> params, Config config) {
        this.name = name;
        if (params == null) {
            params = Collections.emptyList();
        }
        this.params = params;
        if (config == null) {
            config = new Config();
        }
        this.config = config;
    }

    /**
     * 执行命令
     *
     * @param args 命令参数
     * @return 命令执行结果
     */
    public abstract Object execute(Map<String, Object> args);

    public CommandMethods toCommandMethods() {
        return new CommandMethods(input -> {
            return execute(config.parser.parse(this, input.args()));
        }, name -> {
            // 由子类实现
            return Collections.emptyList();
        });
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Config {
        /**
         * 忽略未知的选项
         */
        boolean ignoreUnknownOpt = false;

        /**
         * 忽略未知的参数
         */
        boolean ignoreUnknownParam = false;

        /**
         * 忽略重复的参数（针对参数不可多次取值的情况）
         * 如果忽略，取决于解析器逻辑（一般取最后一次参数取值）
         */
        boolean ignoreRepeatParam = false;

        ParamsParser parser = new DefaultParamsParser();
    }
}
